﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace DeviceDemo
{ 
    /// <summary>
    /// 机台的侦听服务，建议每个工序都使用不同的端口号进行侦听，提高吞吐性能 
    /// </summary>
    internal class ListenerService 
    { 
        private bool run = true;
       
        public  void  Start()
        { 
            UdpClient udpClient = new UdpClient(8080);  //侦听端口
            IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, 0);
            while (run)
            {
                try
                {
                    byte[] buffer = udpClient.Receive(ref iPEndPoint);
                    string ip = iPEndPoint.Address.ToString();
                  
                    if (buffer != null   )
                    {
                        _= 处理数据(buffer, ip);
                    }
                }
                catch { }
            }
            udpClient.Close();
        }
         
        Task 处理数据(byte[] buffer,string IP)
        {
            var data= 解析数据(buffer);
            if (data == null) return Task.CompletedTask;

            data.IP = IP;
            DataQueue.Push(data);
            return Task.CompletedTask;
        }


        DeviceReceiveData? 解析数据(byte[] buffer)
        {
            //不同协议不同的解析，此处不表
            return new DeviceReceiveData();
        }


    }


}
